﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.IO.Ports;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using MasterDatabase;
using System.Collections;
using System.Threading;
using LayoutControl;

namespace JobsDisplay
{
    public partial class Form1 : SQL_APPL
    {
        private Thread Display_Thread;

        private void Tracking_MSNV_Txt_TextChanged(object sender, EventArgs e)
        {
            string msnv = Tracking_MSNV_Txt.Text.Trim();
            if (msnv != "")
            {
                string empl_name = Get_Empl_Name(msnv);
                Tracking_EmplName_Lbl.Text = empl_name;
                Tracking_Date_Lbl.Text = DateTime.Now.ToString("dd MMM yyyy");
                Tracking_Shift_LBL.Text = Get_Shift_ID(DateTime.Now);
                string wst_id, wst_list = "";
                string cur_empl, out_time;

                // HH02_09
                if (Display_Thread != null)
                {
                    Display_Thread.Abort();
                }

                // Get_Cur_WST(Cur_Line_ID, DateTime.Now);

                Create_Tracking(msnv); //The first show of layout. Just only the WST that activated
                Load_WST_Tracking(Cur_Line_ID, "", DateTime.Now);
                BindingSource bs = new BindingSource();
                bs.DataSource = WST_Tracking_dtb;
                Tracking_GridView.DataSource = bs;
                Tracking_GridView_BindingContextChanged(null, null);

                // Create WST Ready List
                foreach (DataRow row in WST_Tracking_dtb.Rows)
                {
                    wst_id = row["WST_ID"].ToString().Trim();
                    cur_empl = row["Empl_ID"].ToString().Trim();
                    out_time = row["To_Time"].ToString().Trim();
                    if ((cur_empl != "") && (out_time == ""))
                    {
                        wst_list += wst_id + "$" + cur_empl + ";";
                    }
                }




                Display_Thread = new Thread(() => Show_Display(wst_list));//The first show of layout with all ready layout
                Display_Thread.SetApartmentState(ApartmentState.STA);
                Display_Thread.Start();
            }
        }

        private void Show_Display(string wst_list)
        {
            //Layout_HH02 layout_Display = new Layout_HH02("", wst_list, "HH02 Job Assignment");
            ////Sample of using Layout_HH02_Controller
            //Layout_HH02_Controller ctrl = new Layout_HH02_Controller(this);

            //Dho: Extra setting to customize if needed
            // ctrl.SetInActiveColor(Color.LightGreen);

            frmClient frmLayout = new frmClient(Cur_Line_ID);
            Line line = frmLayout.GetLineInstant();

            //line.InActiveColor = Color.Red;
            //line.ReadyColor = Color.LightGreen;
            //line.ActiveColor = Color.LightYellow;
            //line.AltColorForBlinking = Color.Yellow;
            //line.BlinkingSpeed = 600;
            line.SetInactiveLine();
            //line.SetActiveWST(Cur_WST_ID, "");

            //foreach (Control control in this.Controls)
            //{
            //    if ((control is Button) && (control != Confirm_BT))
            //    {
            //        control.Click += new EventHandler(control_Click);
            //        this.AcceptButton = (Button)control;
            //        ((Button)control).DialogResult = DialogResult.OK;
            //    }
            //}

            //When employee scan their name card, the system know
            //- which work station name is suitable for this employee
            //- Highlight the position of workstation in the line for employee to recognize where to go
            //try
            //{
            //    line.SetActive(Active_Node);
            //}
            //catch
            //{
            //    line.SetInactiveLine();
            //}

            line.SetInactiveLine();

            string[] ready_nodes = wst_list.Split(';');
            if (ready_nodes.Count() > 0)
            {
                foreach (string ready_node in ready_nodes)
                {
                    //node = ready_node.Replace('_', '-');
                    string[] data = ready_node.Split('$');

                    if (data.Length == 2)
                    {
                        string nodeID = data[0];
                        string msnv = data[1];

                        if (nodeID != "")
                        {
                            line.SetReady_WST(nodeID, msnv);                        
                        }
                    }
                }
            }


            frmLayout.ShowDialog();
        }


        private bool Create_Tracking(string msnv)
        {
            DateTime date = DateTime.Now;
            string line_id;
            string wst_id;
            bool exist = false;
            string plan_wst = "";

            WST_Status wst_status;
            string[] wst_list;
            string empl_name = "";

            string wst_list_a = "";
            string cur_empl, out_time;

            Load_List_of_WST(Cur_Line_ID);
            int total = List_WST_dtb.Rows.Count;
            Cur_WST_ID = "";
            
            Load_Cur_JobsPlan(msnv, date);
            if ((Cur_JobsPlan_dtb != null) && (Cur_JobsPlan_dtb.Rows.Count > 0))
            {
                plan_wst = Cur_JobsPlan_dtb.Rows[0]["WST_ID"].ToString().Trim();
                empl_name = Cur_JobsPlan_dtb.Rows[0]["Empl_Name"].ToString().Trim();
            }

            wst_list = new string[total];
            for (int i = 0; i < total; i++)
            {
                wst_list[i] = List_WST_dtb.Rows[i]["WST_ID"].ToString().Trim();
                if ((plan_wst == wst_list[i]) && (plan_wst != ""))
                {
                    Cur_WST_ID = plan_wst;
                    // empl_name = List_WST_dtb.Rows[i]["Empl_Name"].ToString().Trim();
                }
            }


            if (Cur_WST_ID == "")
            {
                Load_WST_Tracking(Cur_Line_ID, "", DateTime.Now);

                // Create WST Ready List
                foreach (DataRow row in WST_Tracking_dtb.Rows)
                {
                    wst_id = row["WST_ID"].ToString().Trim();
                    cur_empl = row["Empl_ID"].ToString().Trim();
                    out_time = row["To_Time"].ToString().Trim();
                    if ((cur_empl != "") && (out_time == ""))
                    {
                        wst_list_a += ";" + wst_id + "$" + cur_empl;
                    }
                }

                MessageBox.Show("Your data does not exist in this Line.\nPlease check with your Manager", "Warning");
                return false;

                //Layout_HH02 select_wst_Dialog = new Layout_HH02("", wst_list_a, "Please Select Work Station");
                //if (select_wst_Dialog.ShowDialog() == DialogResult.OK)
                //{
                //    Cur_WST_ID = select_wst_Dialog.WST_Selected;
                //}
            }

            if ((Cur_WST_ID != null) && (Cur_WST_ID != ""))
            {
                Close_Logger_Comport();

                frmClient frmLayout = new frmClient(Cur_Line_ID);
                Line line = frmLayout.GetLineInstant();
                line.SetActiveWST(Cur_WST_ID, "");
                frmLayout.ShowDialog();

                //Layout_HH02 layout_Display = new Layout_HH02(Cur_WST_ID, "", "Your Work Station");
                //layout_Display.ShowDialog();


                Open_Logger_Comport();

                // Load_All_Empl_List();
                // if (Is_exist_Empl_List(msnv) == true)
                {
                    Load_Cur_JobsPlan(msnv, date);

                    Load_Job_Tracking(msnv, date);

                    // Close Current Line 
                    foreach (DataRow row in JobsTracking_dtb.Rows)
                    {
                        line_id = row["LineID"].ToString().Trim();
                        wst_id = row["WST_ID"].ToString().Trim();
                        if (line_id != Cur_Line_ID)
                        {
                            row["To_Time"] = DateTime.Now.TimeOfDay;
                        }

                        if (line_id == Cur_Line_ID)
                        {
                            exist = true;
                            if (Setting_Out_Check.Checked == true)
                            {
                                row["To_Time"] = DateTime.Now.TimeOfDay;
                            }
                        }
                    }

                    // add new record
                    if ((exist == false) && (Setting_In_Check.Checked == true))
                    {
                        wst_status = Get_WST_Status(Cur_Line_ID, Cur_WST_ID, DateTime.Now);
                        DataRow new_record = JobsTracking_dtb.NewRow();
                        new_record["Date"] = DateTime.Now.Date;
                        new_record["PartNumber"] = wst_status.Part;
                        new_record["Empl_ID"] = msnv;
                        new_record["Empl_Name"] = empl_name;// Get_Empl_Name(msnv);
                        new_record["LineID"] = Cur_Line_ID;
                        new_record["LineName"] = wst_status.Line_Name;
                        new_record["WST_ID"] = Cur_WST_ID;
                        new_record["WST_Name"] = wst_status.WST_Name;
                        new_record["Shift_Name"] = Get_Shift_ID(DateTime.Now);
                        //new_record["From_Time"] = DateTime.Now.ToString("HH:mn:ss");
                        new_record["From_Time"] = DateTime.Now.TimeOfDay;
                        // new_record["To_Time"] = DateTime.Now.TimeOfDay;

                        // new_record["TrackingType"] = msnv;
                        new_record["ModifyDate"] = DateTime.Now;
                        new_record["CreateDate"] = DateTime.Now;
                        // new_record["Note"] = msnv;

                        JobsTracking_dtb.Rows.Add(new_record);
                    }

                    Update_SQL_Data(JobsTracking_da, JobsTracking_dtb);

                    return true;
                }
                //else
                //{
                //    MessageBox.Show("Do not have personal information for Employeed: " + msnv, "Warning");
                //}
            }
            return false;
        }

        private void Tracking_GridView_BindingContextChanged(object sender, EventArgs e)
        {
            string col_name;
            if (Tracking_GridView.DataSource == null) return;

            foreach (DataGridViewColumn col in Tracking_GridView.Columns)
            {
                col_name = col.Name.ToString().Trim();
                if ((col_name == "Empl_ID") || (col_name == "Empl_Name") || (col_name == "Shift_Name")
                    || (col_name == "WST_ID") || (col_name == "LineID") // || (col_name == "ModifyDate")
                    || (col_name == "From_Time") || (col_name == "To_Time") || (col_name == "ModifyDate"))
                {
                    col.Visible = true;
                }
                else
                {
                    col.Visible = false;
                }
            }
            YourJob_GridView.AutoResizeColumns();
        }

    }
}